<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\OrderTemporary;
use app\common\model\ProductCart;
use app\common\model\ProductSpec;
use app\common\tool\Result;
use think\Response;

class Cart extends Base
{
    public function index(): Response
    {
        $list = ProductCart::field('id,pid,spec,num')->where(['uid' => $this->user->id])
            ->order('update_time desc,id desc')->select();
        foreach ($list as $key => $item) {
            if (empty($item->product)) {
                ProductCart::destroy(['id' => $item->id], true);
                unset($list[$key]);
                continue;
            }
            $item->title = $item->product->title;
            $item->icon = $item->product->icon;
            $item->price = $item->product->price;
            $item->vip_price = $item->product->vip_price;
            if ($item->spec) {
                $specInfo = ProductSpec::where(['pid' => $item->pid, 'merge_title' => $item->spec])->find();
                if (empty($specInfo)) {
                    ProductCart::destroy(['id' => $item->id], true);
                    unset($list[$key]);
                    continue;
                }
                $item->icon = $specInfo->icon ?: $item->product->icon;
                $item->price = $specInfo->price;
                $item->vip_price = $specInfo->vip_price;
            }
            unset($item->product);
        }

        return Result::success('success', array_values($list->toArray()));
    }

    public function add(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(ProductCart::add($param, $this->user));
    }

    public function edit(): Response
    {
        $param = $this->request->post();
        if ($param['type'] == 3) {
            $param['cart_id'] = $param['id'] ? explode(',', $param['id']) : '';
        }

        return Result::fastReturn(ProductCart::edit($param, $this->user));
    }

    public function submit(): Response
    {
        $param = $this->request->post();
        $param['type'] = 2;
        $param['cart_id'] = $param['cart_id'] ? explode(',', $param['cart_id']) : '';

        return Result::fastReturn(OrderTemporary::setTemporary($param, $this->user));
    }
}